﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Util;
using log4net;
using System.Reflection;

namespace Crawler.TaskControl
{
    public class TaskManager
    {
        private static ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public List<CrawlTask> Tasks { get; set; }

        public TaskManager() 
        {
            LoadTasks();
        }

        private void LoadTasks() 
        {
            try
            {
                Tasks = XmlUtil.XmlDeserialize(typeof(List<CrawlTask>), "input\\tasks.xml") as List<CrawlTask>;
                log.Info("load tasks success");
            }
            catch (Exception e)
            {
                log.Error(e.Message);
                throw new Exception("input\tasks.xml not found");
            }
        }

        public List<CrawlTask> GetMyTasks() 
        {
            List<int> range = LoadTaskRange();
            var query = from task in Tasks
                        where range.Contains(task.ID)
                        select task;
            List<CrawlTask> list = query.ToList();
            return list;
        }

        private List<int> LoadTaskRange()
        {
            try
            {
                String str = ConfigUtil.GetAppSetting("taskIdRange");
                String[] arr = str.Split('~');
                int min = int.Parse(arr[0]);
                int max = int.Parse(arr[1]);
                int count = max - min;
                List<int> ie = Enumerable.Range(min, count).ToList();
                log.Info("load tasks as app.config/appsetting/taskIdRange is specified");
                return ie;
            }
            catch (Exception e)
            {
                log.Info(e.Message);
                throw new Exception("app.config/appsetting/taskIdRange error") ;
            }
        }

    }
}
